import React, { Component } from 'react'
import { fetchData  } from "../AjaxConsumer";
import { Tree, Spin, Modal } from 'antd';
import Actions from '../../actions';
import store from '../../stores'
const TreeNode = Tree.TreeNode;

export default class BaseDataTreeComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            expandedKeys: this.props.expandedKeys ? this.props.expandedKeys : [],
            autoExpandParent: true,
            checkedKeys: this.props.checkedKeys ? this.props.checkedKeys : [],
            selectedKeys: this.props.selectedKeys ? this.props.selectedKeys : [],
            storeResData: null,
        }
    }
    //请求，刷新函数
    refleshData = () => {
        //发送ajax请求基础树数据
        let defaultOptions= {
            url: this.props.url,        //请求地址
            type: 'post',    //请求方式
            condition: {},   //请求条件
        };
        fetchData(this,defaultOptions,(res)=>{
            //处理checkedKeys，只输出全选中的
            let unTargetc = this.props.checkedKeys?this.props.checkedKeys : []
            //  console.log('处理前的选中节点',unTargetc)
            let targetc = this.handleTargetc(res.data,unTargetc);
            // console.log('处理后的选中节点',targetc)
            this.setState({
                storeResData: res.data,
                checkedKeys: targetc,
            })
        })

    }
    componentDidMount(){
        this.refleshData();
            
    }
    handleTargetc = (res,targetc) => {
            let dataArrId = [];
            let treeId = this.props.treeId;
            let treeChildren = this.props.treeChildren;
            let loop2 = (data, dataArrId, parentID) => {
                data.map((item) => {
                    if (item[treeChildren]) {
                        let childIds = [];
                        let keyId = item[treeId];

                        item[treeChildren].map( (e) => {
                            childIds.push(e[treeId]);
                        });
                        if(typeof(parentID) == "undefined"){
                            parentID = -1;
                        }
                        dataArrId.push({
                            key: keyId,
                            value: childIds,
                            parentID: parentID
                        })

                        loop2(item[treeChildren], dataArrId, keyId)
                    }
                });
            }
            if (this.props.checkable){
                
                //加入默认选中父节点
                for (let i = 0; i < res.length; i++){ //最外层，个数控制（有几个系统）
                    let flagBreak = false;
                    for(let j = 0; j < res[i].length; i++){ //每个系统的每个模块
                        for(let k = 0; k < targetc.length; k++){//若子节点有选中的，则根节点也传入
                            if(res[i][j][treeId] == targetc[k]){
                                targetc.push(item[treeId])
                                flagBreak = true;
                                break
                            }
                        }
                        if(flagBreak == true){
                            return ;
                        }
                    }
                }                
                let gData = res;
                if(gData!=null){
                    console.log('gData===', gData)
                    loop2(gData, dataArrId);
                }
                //得到半选
                console.log('dataArrId：===', JSON.stringify(dataArrId))
                console.log('targetc===',targetc)
                let halfIds = gethalfIds(dataArrId, targetc);
                console.log('半选：===',halfIds)
                //总数据targetc去掉半选
                let tempA, tempB;
                for (let i = targetc.length - 1; i >= 0; i--) {
                    tempA = targetc[i];
                    for (let j = halfIds.length - 1; j >= 0; j--) {
                        tempB = halfIds[j];
                        if (tempA == tempB) {
                            targetc.splice(i, 1);
                            halfIds.splice(j, 1);
                            break;
                        }
                    }
                }
                
                return targetc;
            }
    }
    //拿到树顶级节点的ID数组
    getTopTreeId = () => {
        let treeId = this.props.treeId;
        let treeChildren = this.props.treeChildren;
        let storeResData = this.state.storeResData;
        let topTreeId = [];
        storeResData.map((item) => {
            topTreeId.push(item[treeId]);
        })
        return topTreeId;
    }
    //展开/收起节点时触发
    onExpand = (expandedKeys) => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    //点击复选框触发
    onCheck = (checkedKeys,info) => {
        this.setState({
            checkedKeys: checkedKeys,
            halfCheckedKeys: info.halfCheckedKeys,
            //parentKeys: info.halfCheckedKeys,
            selectedKeys: [],
        });
        let treeId = this.props.treeId;
        let allCheckedKeys = [...checkedKeys,...info.halfCheckedKeys]
        let allCheckedKeysExceptRoot = [];
        let storeResData = this.state.storeResData;
        storeResData.map((item)=>{
            let storeResDataRootKey = item[treeId];
            for(let j = 0; j < allCheckedKeys.length; j++){
                //如果有和根节点一样的key，则剔除
                if(storeResDataRootKey == allCheckedKeys[j]){
                    allCheckedKeys.splice(j, 1);
                }
            }
        })
        // console.log('allCheckedKeys',allCheckedKeys)

        if (this.props.handCheckedKeys) {
            this.props.handCheckedKeys(allCheckedKeys);
        }
    }
    componentWillReceiveProps(nextProps) {
        //处理checkedKeys，只输出全选中的
        let unTargetc = nextProps.checkedKeys
        // console.log('处理前的选中节点',unTargetc)
        let targetc = this.handleTargetc(this.state.storeResData,unTargetc);
        // console.log('处理后的选中节点',targetc)
        this.setState({
            // storeResData: res.data,
            checkedKeys: targetc,
        })
        // this.setState({
        //     checkedKeys: nextProps.checkedKeys,
        // });
    }
    render() {
        let gData = this.state.storeResData ? this.state.storeResData : null;
        let treeId = this.props.treeId;
        let treeName = this.props.treeName;
        let treeChildren = this.props.treeChildren;
        let loop = data => data.map((item) => {
            if (item[treeChildren]) {
                return (
                    <TreeNode key={item[treeId]} title={item[treeName]}>
                        {loop(item[treeChildren])}
                    </TreeNode>
                );
            }
            return <TreeNode key={item[treeId]} title={item[treeName]} />;
        });
        let myTree;
        // console.log(`我想知道的${this.state.checkedKeys }`)
        if(gData != null){
            myTree =  <Tree
                            checkable = {this.props.checkable ? true : false}
                            onExpand={this.onExpand}
                            onCheck={this.onCheck}
                            selectedKeys={this.state.selectedKeys}
                            checkedKeys = {this.state.checkedKeys}
                            defaultExpandedKeys = {this.getTopTreeId()}
                        >
                            {loop(gData)}
                        </Tree>
        } else {
            myTree = <Spin size="large" />
        }
        return(
                <div>{myTree}</div>
        )
    }
}
function gethalfIds(dataArrId, checkIds) {
    var myMap = new Map();
    dataArrId.map( (item) => {
        let key = item.key;
        let parentID = item.parentID;
        let value = item.value;
        let size = value.length;
        let forSize = 0;
        value.map( (e) => {
            let index = checkIds.indexOf(e);
            if(index < 0){
                forSize += 1;
            }
        });
        if(size != forSize){
            myMap.set(key, parentID);
        }
    });
    let halfIds = [], halfParentIds = [];
    for(let [key, value] of myMap) {
        halfIds.push(key);
        if(halfParentIds.indexOf(value) < 0){
            halfParentIds.push(value);
        }
    }
    halfParentIds.map( (halfItem) => {
        dataArrId.map( (item) => {
            let key = item.key;
            if(key == halfItem){
                let value = item.value;
                let size = value.length;
                value.map( (e) => {
                    let index = halfIds.indexOf(e);
                    if(index > -1){
                        if(halfIds.indexOf(key) < -1){
                            halfIds.push(key);
                        }
                    }
                });
            }
        });
    });
    return halfIds;
}
